package com.chuiyuan.study;

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by chuiyuan on 3/9/16.
 */
public class ReadWriteLockTest {
    public static void main(String [] args){
        final Data data = new Data();
        for (int i=0;i<5;i++){
            new Thread(new Runnable() {
                public void run() {
                    data.set(new Random().nextInt(30));
                }
            }).start();
        }
        for (int i=0;i<3;i++){
            new Thread(new Runnable() {
                public void run() {
                    data.get();
                }
            }).start();
        }
    }
}

class Data {
    private int data ;
    private ReadWriteLock rwl =new ReentrantReadWriteLock();

    public void set (int data ){
        rwl.writeLock().lock();//get write lock
        try {
            System.out.println(Thread.currentThread().getName()+" ready to write data");
            try {
                Thread.sleep(20);
            }catch (InterruptedException e ){
                e.printStackTrace();
            }
            this.data = data ;
            System.out.println(Thread.currentThread().getName()+"write data:"+data);
        }finally {
            rwl.writeLock().unlock(); //release write lock
        }
    }

    public int get(){
        rwl.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+" ready to read ");
            try {
                Thread.sleep(20);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" read data: "+data);
            return data;
        }finally {
            rwl.readLock().unlock();
        }
    }
}
